<template>
  <div class="app-container">
    <split-pane :min-percent='10' :default-percent='20' split="vertical">
      <template slot="paneL">
        <el-card class="m-l-5">
          <el-input v-model="filterTagText" class="m-b-20" placeholder="搜索标签" />
          <el-tree
            ref="tagTree"
            node-key="id"
            :data="treeData"
            :props="treeProps"
            :filter-node-method="filterTagNode"
            class="filter-tree"
            default-expand-all
            highlight-current
            :expand-on-click-node="false"
            check-on-click-node
            @node-click="selectTag"
            @node-contextmenu="rightClickTree"
          />
          <div class="tree_right_menu" ref="tree_right_menu" v-show="showTreeRightMenu">
            <ul>
              <li class="m-b-10">
                <el-popover width="300" v-model="cur_node.visible">
                  <el-row>
                    <el-col :span="24">
                      <el-input v-model="cur_node.name" />
                    </el-col>
                    <el-col :span="24" class="m-t-10 m-b-10">
                      <el-button size="mini" type="success" plain @click="() => editTag()">更新</el-button>
                      <el-button size="mini" type="primary" plain @click="() => addTag()">创建子标签</el-button>
                    </el-col>
                  </el-row>
                  <el-link slot="reference" size="mini" type="primary" icon="el-icon-edit">编辑</el-link>
                </el-popover>
              </li>
              <li><el-link size="mini" type="danger" icon="el-icon-remove" @click.stop="deleteTag()">删除</el-link></li>
            </ul>
          </div>
        </el-card>
      </template>

      <template slot="paneR">
        <!-- 搜索区域 -->
        <el-card style="margin:0 0 5px 5px" v-show="showSearch">
          <el-form ref="queryForm" :inline="true" :model="queryData">
            <el-tag v-if="selectedTagText" class="m-r-20">{{ selectedTagText }}</el-tag>
            <el-form-item label="题目名称" prop="Q_content_S_LK">
              <el-input v-model="queryData.Q_content_S_LK" placeholder="题目名称" />
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker v-model="queryData.Q_createTime_D_GE" class="width-130" type="date" value-format="yyyy-MM-dd" placeholder="开始时间" />
              -
              <el-date-picker v-model="queryData.Q_createTime_D_LE" class="width-130" type="date" value-format="yyyy-MM-dd" placeholder="结束时间" />
            </el-form-item>
            <el-form-item class="fr p-r-10">
              <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
                搜索
              </el-button>
              <el-button class="filter-item m-l-10" type="info" round icon="el-icon-refresh" @click="handleClear">
                清空
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <!-- table区域 -->
        <el-card class="m-l-5">
          <el-row :gutter="10" class="m-b-5">
            <el-col :span="1.5">
              <el-button v-permission="['training:question:add']" type="primary" size="mini" plain icon="el-icon-plus" @click="handleInfo()">
                新增
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-permission="['training:question:delete']" v-if="selectionData.length > 0" type="danger" size="mini" plain icon="el-icon-delete" @click="handleDelete()">
                删除
              </el-button>
            </el-col>
            <table-toolbar :showSearch.sync="showSearch" @refresh="getTableData" />
          </el-row>
          <el-table
            ref="question_table"
            v-loading="tableLoading"
            :data="tableData"
            element-loading-text="加载中"
            border
            fit
            highlight-current-row
            show-overflow-tooltip
            height="100px"
            v-el-height-adaptive-table="{bottomOffset: 110}"
            @sort-change="sortChange"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="40" />
            <el-table-column align="center" label="题目" prop="content" sortable show-overflow-tooltip />
            <el-table-column align="center" label="类型" prop="type" sortable width="90">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.type == '0'" type="primary">单选</el-tag>
                <el-tag v-if="scope.row.type == '1'" type="primary">多选</el-tag>
                <el-tag v-if="scope.row.type == '2'" type="primary">判断</el-tag>
                <el-tag v-if="scope.row.type == '3'" type="primary">填空</el-tag>
                <el-tag v-if="scope.row.type == '4'" type="primary">主观</el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" label="难度" prop="difficulty" sortable width="150" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-rate disabled text-color="#ff9900" :value="scope.row.difficulty"></el-rate>
              </template>
            </el-table-column>
            <el-table-column align="center" label="分值" prop="score" width="90" show-overflow-tooltip />
            <el-table-column align="center" label="操作" width="160" fixed="right">
              <template slot-scope="scope">
                <el-link class="m-r-10" type="primary" icon="el-icon-view" @click="handlePreview(scope.row.questionId)">预览</el-link>
                <el-dropdown>
                  <span class="el-dropdown-link" style="font-size: smaller">
                    更多<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-permission="['training:question:delete']">
                      <el-link icon="el-icon-view" size="mini" @click="handleInfo(scope.row.questionId)">编辑</el-link>
                    </el-dropdown-item>
                    <el-dropdown-item v-permission="['training:question:delete']">
                      <el-link type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row.questionId)">删除</el-link>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData" />
        </el-card>
      </template>
    </split-pane>

    <el-dialog v-el-drag-dialog :title="selectedTagText + '试题预览'" :visible.sync="showQuestionPreview" :append-to-body="false">
      <question-preview ref="question_preview" :question-info="questionInfo" :show-number="false" :show-answer="true" />
    </el-dialog>

    <el-dialog v-el-drag-dialog :title="selectedTagText + '试题编辑'" :visible.sync="showQuestionEdit" :append-to-body="false">
      <question-edit ref="question_edit" @update="handleFilter();showQuestionEdit=false;" />
    </el-dialog>
  </div>
</template>

<script>
import { tagTreeData, questionTable, questionDelete, tagSave, tagDelete } from '@/api/training/exam'
import SplitPane from 'vue-splitpane'
import QuestionPreview from './preview'
import QuestionEdit from './form'

export default {
  components: {
    SplitPane,
    QuestionPreview,
    QuestionEdit
  },
  data() {
    return {
      filterTagText: '',
      selectedTagText: '',
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      cur_node: {},
      showSearch: true,
      queryData: {
        Q_tagId_S_EQ: undefined,
        Q_content_S_LK: undefined,
        Q_createTime_D_GE: undefined,
        Q_createTime_D_LE: undefined
      },
      tableLoading: false,
      tableData: [],
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: undefined,
        order: undefined
      },
      selectionData: [],
      questionInfo: {
        questionId: undefined,
        type: '0',
        optionType: '0',
        content: undefined,
        analysis: undefined,
        answer: undefined,
        difficulty: 1,
        score: 1,
        tagId: undefined,
        options: []
      },
      showTreeRightMenu: false,
      showQuestionPreview: false,
      showQuestionEdit: false
    }
  },
  watch: {
    filterTagText(val) {
      this.$refs.tagTree.filter(val)
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.getTreeData()
      this.getTableData()
    },
    filterTagNode(value, data) {
      if (!value) return true
      return data.title.indexOf(value) !== -1
    },
    rightClickTree(e, data, node) {
      this.cur_node = undefined
      this.cur_node = this.$api.objectExtend(this.cur_node, data, '')
      this.showTreeRightMenu = true
      this.$refs.tree_right_menu.style.left = e.clientX - 280 + 'px'
      this.$refs.tree_right_menu.style.top = e.clientY - 80 + 'px'
      document.addEventListener('click', this.closeRightClickTree)
    },
    closeRightClickTree() {
      this.showTreeRightMenu = false
      document.removeEventListener('click', this.closeRightClickTree)
    },
    selectTag(data, node) {
      if (data.id !== '0') {
        this.queryData.Q_tagId_S_EQ = data.id
        this.selectedTagText = data.name
        this.handleFilter()
      }
    },
    addTag() {
      tagSave({
        tagId: undefined,
        parentId: this.cur_node.id,
        tagName: this.cur_node.name
      }).then(response => {
        this.$modal.msgSuccess(response.msg)
        this.getTreeData()
        this.cur_node.visible = false
      })
    },
    editTag() {
      tagSave({
        tagId: this.cur_node.id,
        parentId: this.cur_node.pid,
        tagName: this.cur_node.name
      }).then(response => {
        this.$modal.msgSuccess(response.msg)
        this.getTreeData()
        this.cur_node.visible = false
      })
    },
    deleteTag() {
      this.$confirm(`是否删除标签 [${this.cur_node.name}]?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        tagDelete({
          ids: this.cur_node.id
        }).then(response => {
          this.$modal.msgSuccess(response.msg)
          this.getTreeData()
        }).catch(e => {})
      }).catch(e => {})
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getTableData()
    },
    handleClear() {
      this.$refs.queryForm.resetFields()
      this.queryData.Q_tagId_S_EQ = undefined
      this.queryData.Q_createTime_D_GE = undefined
      this.queryData.Q_createTime_D_LE = undefined
      this.getTableData()
    },
    getTreeData() {
      this.treeData = []
      tagTreeData({
        from: 'vue'
      }).then(response => {
        this.treeData = response
      }).catch(e => {})
    },
    getTableData() {
      const query = Object.assign(this.tableQuery, this.queryData)
      this.tableLoading = true
      questionTable(query).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
        this.$refs.question_table.bodyWrapper.scrollTop = 0
      }).catch(e => {
        this.tableLoading = false
      })
    },
    sortChange(data) {
      const { prop, order } = data
      this.tableQuery.sort = prop
      if (order === 'ascending') {
        this.tableQuery.order = 'asc'
      } else {
        this.tableQuery.order = 'desc'
      }
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.selectionData = val
    },
    handlePreview(questionId) {
      this.showQuestionPreview = true
      this.$nextTick(() => {
        this.$refs.question_preview.init(questionId)
      })
    },
    handleInfo(id) {
      if (!id && !this.queryData.Q_tagId_S_EQ) {
        this.$modal.msgWarning('请先选择标签')
        return
      }
      this.showQuestionEdit = true
      this.$nextTick(() => {
        this.$refs.question_edit.init(id, this.queryData.Q_tagId_S_EQ)
      })
    },
    handleDelete(id) {
      const ids = this.selectionData.map(function(question, index) {
        return question.questionId
      }).join(',')

      id = id || ids
      if (!id || id.length === 1) {
        this.$modal.msgWarning('请先选中数据项')
        return
      }

      this.$confirm('是否删除所选用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        questionDelete({
          ids: id
        }).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess(response.msg)
        }).catch(e => {})
      }).catch(e => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.line {
  text-align: center;
}
.tree-node-extra {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.tree_right_menu {
  position: absolute;
  background: rgb(239, 239, 241);
  border: 1px solid rgb(241, 241, 241);
  border-radius: 2%;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 30%);
}
.tree_right_menu ul {
  width: 100%;
  height:100%;
  list-style: none;
  margin: 0;
  padding: 5px;
  border-radius: 2%;
}
</style>
